'''
Descripttion: 模拟交易资金划转功能
Author: yubo
Date: 2021-05-25 09:58:10
LastEditTime: 2022-03-09 17:41:49
Keyword: mysql, http
'''


import requests
import sys
import pymysql

'''
数据库信息
'''
config={
    "host":"101.226.207.176",
    "user":"moni",
    "password":"Moni@1234",
    "database":"moni"
}

#用以资金转账的账号
fund_option_account = 'ToTransferFound'
fund_stock_account = 'e7565efcacf34457ade0328ad676d5c7'

#期权的http请求地址
option_addr = "http://101.226.207.134:8080/lan/moneyTransfer"
#股票的http请求地址
stock_addr = "http://101.226.207.134:8090/lan/moneyTransfer"

'''
从mysql数据库获取 手机号对应的 账号信息
返回[期权账号，股票账号]
'''
def get_accounts(mobileno):
    con = pymysql.connect(host=config['host'], database = config['database'],
    charset = 'utf8', user = config['user'], password = config['password'])

    #sql语句
    sql_str = R"select OptionAccount,StockAccount from t_user where UserID= '%s';" % mobileno

    try:
        with con.cursor() as cursor:
            cursor.execute(sql_str)
            results = cursor.fetchall()
            accs = []
            for elem in results:
                accs.append(elem[0])
                accs.append(elem[1])
                break
            return accs
    finally:
        con.close()


def form_request(dest_account, busi_type, funds):
    url_str = ""
    if busi_type == 'option':
        params = R"accountCounter=option&accountNo=%s&money=%d&outAccountCounter=1&outAccountNo=%s&side=1"%(dest_account, funds, fund_option_account)
        url_str = option_addr + '?' +params
    elif busi_type == 'stock':
        params = R"accountCounter=stock&accountNo=%s&money=%d&outAccountCounter=1&outAccountNo=%s&side=1"%(dest_account, funds, fund_stock_account)
        url_str = stock_addr + '?' +params
    else:
        pass

    print(url_str)
    return url_str


def trans_fund(mobileno, busi_type, funds):
    accounts = get_accounts(mobileno)
    result = ""
    if busi_type == 'option':
        result = requests.get(form_request(accounts[0], busi_type, funds))
    elif busi_type == 'stock':
        result = requests.get(form_request(accounts[1], busi_type, funds))
    else:
        pass
    print(result.text)


if __name__ == '__main__':
    if len(sys.argv) != 4:
        print("usage: python TransFund.py [mobileno] [option/stock] [money]")
        sys.exit()

    mobileno = sys.argv[1]
    busi_type = sys.argv[2]
    funds = sys.argv[3]

    trans_fund(mobileno, busi_type, int(funds))
    
    